from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from .. import models, schemas
from datetime import datetime

def create_friend_request(db: Session, from_user_id: str, to_user_id: str):
    """创建好友请求"""
    # 检查是否向自己发送请求
    if from_user_id == to_user_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能向自己发送好友请求"
        )
    
    # 检查是否已经是好友
    if check_if_friends(db, from_user_id, to_user_id):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="已经是好友关系"
        )
    
    # 检查是否已有待处理的好友请求
    existing_request = db.query(models.FriendRequest).filter(
        models.FriendRequest.from_user_id == from_user_id,
        models.FriendRequest.to_user_id == to_user_id,
        models.FriendRequest.status == "pending"
    ).first()
    
    if existing_request:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="已存在待处理的好友请求"
        )
    
    # 创建新的好友请求
    friend_request = models.FriendRequest(
        from_user_id=from_user_id,
        to_user_id=to_user_id
    )
    db.add(friend_request)
    db.commit()
    db.refresh(friend_request)
    return friend_request

def handle_friend_request(db: Session, request_id: str, user_id: str, accept: bool):
    """处理好友请求"""
    request = db.query(models.FriendRequest).filter(
        models.FriendRequest.friend_req_id == request_id,
        models.FriendRequest.to_user_id == user_id,
        models.FriendRequest.status == "pending"
    ).first()
    
    if not request:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="好友请求不存在或已处理"
        )
    
    # 更新请求状态
    request.status = "accepted" if accept else "rejected"
    
    # 如果接受请求，建立好友关系
    if accept:
        # 获取用户
        from_user = db.query(models.User).filter(models.User.id == request.from_user_id).first()
        to_user = db.query(models.User).filter(models.User.id == request.to_user_id).first()
        
        # 建立双向好友关系
        friendship = models.Friendship(
            user_id=request.from_user_id,
            friend_id=request.to_user_id
        )
        db.add(friendship)
        
        reverse_friendship = models.Friendship(
            user_id=request.to_user_id,
            friend_id=request.from_user_id
        )
        db.add(reverse_friendship)
    
    db.commit()
    return request

def get_friend_requests(db: Session, user_id: str, is_received: bool = True):
    """获取好友请求列表"""
    if is_received:
        return db.query(models.FriendRequest).filter(
            models.FriendRequest.to_user_id == user_id,
            models.FriendRequest.status == "pending"
        ).all()
    else:
        return db.query(models.FriendRequest).filter(
            models.FriendRequest.from_user_id == user_id
        ).all()

def check_if_friends(db: Session, user_id1: str, user_id2: str) -> bool:
    """检查两个用户是否是好友关系"""
    friendship = db.query(models.Friendship).filter(
        models.Friendship.user_id == user_id1,
        models.Friendship.friend_id == user_id2
    ).first()
    return friendship is not None

def get_user_friends(db: Session, user_id: str):
    """获取用户的好友列表"""
    user = db.query(models.User).filter(models.User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user.friends

def delete_friendship(db: Session, user_id: str, friend_id: str):
    """删除好友关系"""
    # 检查是否是好友
    if not check_if_friends(db, user_id, friend_id):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="该用户不是你的好友"
        )
    
    # 删除双向好友关系
    db.query(models.Friendship).filter(
        models.Friendship.user_id == user_id,
        models.Friendship.friend_id == friend_id
    ).delete()
    
    db.query(models.Friendship).filter(
        models.Friendship.user_id == friend_id,
        models.Friendship.friend_id == user_id
    ).delete()
    
    db.commit()
    return {"message": "好友关系已解除"}

def accept_friend_request(db: Session, request_id: str, user_id: str):
    """接受好友请求的便捷函数"""
    return handle_friend_request(db, request_id, user_id, accept=True)

def reject_friend_request(db: Session, request_id: str, user_id: str):
    """拒绝好友请求的便捷函数"""
    return handle_friend_request(db, request_id, user_id, accept=False) 